﻿@using System
@using CodeBuilder
@using CodeBuilder.Models.TemplateModels
@inherits RazorEngine.Templating.TemplateBase<CodeBuilder.Models.TemplateModels.DtoFileModel>

import { finalize } from 'rxjs/operators';
import { Component, OnInit, Injector } from '@@angular/core';
import {
    @(Model.Name)EditDto,
    @(Model.Name)ServiceProxy,
    CreateOrUpdate@(Model.Name)Input
} from '@@shared/service-proxies/service-proxies';

import { ModalComponentBase } from '@@shared/common/modal-component-base';

@@Component({
    selector: 'createOrEdit@(Model.Name)Modal',
    templateUrl: './create-or-edit-@(Model.Name.ToLower())-modal.component.html',
    styles: [],
})
export class CreateOrEdit@(Model.Name)ModalComponent extends ModalComponentBase implements OnInit {
    @(Model.Name.FirstCharToLower())Id?: number;
    @(Model.Name.FirstCharToLower()): @(Model.Name)EditDto = new @(Model.Name)EditDto();
    saving = false;

    constructor(injector: Injector, private _@(Model.Name.FirstCharToLower())Service: @(Model.Name)ServiceProxy) {
        super(injector);
    }

    ngOnInit() {
        this.init();
    }

    init(): void {
        const self = this;

        self._@(Model.Name.FirstCharToLower())Service.get@(Model.Name)ForEdit(self.@(Model.Name.FirstCharToLower())Id).subscribe(result => {
            self.@(Model.Name.FirstCharToLower()) = result.@(Model.Name.FirstCharToLower());
        });
    }

    save(): void {
        const input: CreateOrUpdate@(Model.Name)Input = new CreateOrUpdate@(Model.Name)Input();
        input.@(Model.Name.FirstCharToLower()) = this.@(Model.Name.FirstCharToLower());
        this.saving = true;
        this._@(Model.Name.FirstCharToLower())Service
            .createOrUpdate@(Model.Name)(input)
            .pipe(finalize(() => (this.saving = false)))
            .subscribe(() => {
                this.notify.success(this.l('SavedSuccessfully'));
                this.success();
            });
    }
}
